package com.ueboot.weishop.service.order.impl;

import com.ueboot.core.repository.BaseRepository;
import com.ueboot.core.service.impl.BaseServiceImpl;
import com.ueboot.weishop.entity.order.OrderEntity;
import com.ueboot.weishop.entity.order.OrderInvoiceEntity;
import com.ueboot.weishop.repository.order.OrderInvoiceRepository;
import com.ueboot.weishop.service.order.OrderInvoiceService;
import com.ueboot.weishop.service.order.OrderService;
import jodd.util.StringUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Example;
import org.springframework.data.domain.ExampleMatcher;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.stereotype.Service;

/**
 * Created by zl  on 2017-11-05 14:45:14.
 *
 * @author zl
 * @since 2.0 by autocode
 */
@Slf4j
@Service
public class OrderInvoiceServiceImpl extends BaseServiceImpl<OrderInvoiceEntity> implements OrderInvoiceService {

    @Autowired
    private OrderInvoiceRepository orderInvoiceRepository;

    @Autowired
    private OrderService orderService;

    @Override
    protected BaseRepository getBaseRepository() {
        return orderInvoiceRepository;
    }

    @Override
    public OrderInvoiceEntity findByOrderOrderNo(String orderNo) {
        return orderInvoiceRepository.findByOrderOrderNo(orderNo);
    }

    @Override
    public OrderInvoiceEntity save(OrderInvoiceEntity s) {
        return orderInvoiceRepository.save(s);
    }

    @Override
    public OrderInvoiceEntity get(Long id) {
        return orderInvoiceRepository.findOne(id);
    }

    @Override
    public Page<OrderInvoiceEntity> findByReq(Pageable pageable, OrderInvoiceEntity params,String orderNo,String vin) {
        OrderInvoiceEntity entity=new OrderInvoiceEntity();
        ExampleMatcher example = ExampleMatcher.matching().withIgnoreNullValues();
        if (StringUtil.isNotBlank(params.getTitleName())) {
            entity.setTitleName(params.getTitleName());
            example.withMatcher("TITLE_NAME", matcher -> matcher.contains());
        }
        if(StringUtil.isNotBlank(params.getInvoiceType())){
            entity.setInvoiceType(params.getInvoiceType());
            example.withMatcher("INVOICE_TYPE",matcher -> matcher.exact());
        }
        if(StringUtil.isNotBlank(orderNo)){
            OrderEntity childEntity=orderService.findByOrderNo(orderNo);
            entity.setOrder(childEntity);
            example.withMatcher("ORDER_ID",matcher -> matcher.exact());
        }
        if(StringUtil.isNotBlank(vin)){
            OrderEntity childEntity=orderService.findBykeyForLimit(vin);
            entity.setOrder(childEntity);
            example.withMatcher("ORDER_ID",matcher -> matcher.exact());
        }

        return orderInvoiceRepository.findAll(Example.of(entity, example), pageable);
    }
}
